import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

let stompClient = {}
const headers = {
  // Authorization: ''
}

function initWebSocket () {
  connection()
}

function connection () {
  // 建立连接对象
  const socket = new SockJS('http://127.0.0.1:8134/information')
  // 获取STOMP子协议的客户对象
  stompClient = Stomp.over(socket)
  stompClient.connect(headers, callSuccess, callError)
}

function callSuccess () {
  console.log('连接成功')
  subscription('/topic/getResponse', (val) => { console.log(val) })
}

function callError (err) {
  console.log('与后端连接失败', err)
}

// 订阅消息
function subscription (socketUrl, callBack) {
  stompClient.subscribe(socketUrl, callBack, headers)
}

// 发送消息
function sendSocket (socketUrl, data) {
  stompClient.send(socketUrl, headers, JSON.stringify(data))
}

// 断开连接
function disconnect () {
  if (stompClient) {
    stompClient.disconnect()
  }
}

export {
  initWebSocket,
  disconnect,
  sendSocket,
  subscription
}
